package com.sunshine.lnuplus.ui.activity

import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.webkit.*
import androidx.appcompat.widget.AppCompatEditText
import androidx.preference.Preference
import com.google.android.material.textfield.TextInputLayout
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.utils.LoadLessonUtils
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.TagHelper
import com.sunshine.lnuplus.utils.WebViewUtils
import com.sunshine.lnuplus.view.DialogWithView
import com.sunshine.lnuplus.view.DialogWithoutView
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_load_school_lesson_web_view.*

class LoadSchoolLessonWebViewActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_load_school_lesson_web_view)

        initView()
    }

    private fun initView() {
        title = "登录"
        StatusBarUtils.setStatusBarWithColor(this, color)
        DialogWithoutView.newInstance(
            "提示",
            resources.getString(R.string.login_message),
            false,
            null,
            null
        ).show(supportFragmentManager, "")

        val bundle = intent.getBundleExtra("bundle")
        WebViewUtils.initWebView(webview_school)
        webview_school.addJavascriptInterface(InJavaScriptLocalObj(), "local_obj")
        webview_school.webChromeClient = object : WebChromeClient(){
            override fun onJsConfirm(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean {
                DialogWithoutView.newInstance(
                    "来自网页的提示",
                    message!!,
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        result?.confirm()
                    },
                    DialogInterface.OnClickListener { _, _ ->
                        result?.cancel()
                    }
                ).show(supportFragmentManager, "")
                return true
            }
        }
        webview_school.loadUrl(bundle.getString("url"))
        fab_toload.setOnClickListener {
            when(bundle.getString("type")){
                "ZF" -> {
                    webview_school.loadUrl("javascript:var ifrs=document.getElementsByTagName(\"iframe\");" +
                            "var iframeContent=\"\";" +
                            "for(var i=0;i<ifrs.length;i++){" +
                            "iframeContent=iframeContent+ifrs[i].contentDocument.body.parentElement.outerHTML;" +
                            "}\n" +
                            "var frs=document.getElementsByTagName(\"frame\");" +
                            "var frameContent=\"\";" +
                            "for(var i=0;i<frs.length;i++){" +
                            "frameContent=frameContent+frs[i].contentDocument.body.parentElement.outerHTML;" +
                            "}\n" +
                            "window.local_obj.showSource(document.getElementsByTagName('html')[0].innerHTML + iframeContent + frameContent);")
                }
                "XQZ" -> {
                    webview_school.loadUrl("${bundle.getString("url")}jsxsd/xskb/xskb_list.do")
                    webview_school.webViewClient = object : WebViewClient(){
                        override fun onPageFinished(view: WebView?, url: String?) {
                            super.onPageFinished(view, url)
                            webview_school.loadUrl("javascript:window.local_obj.showSource(document.getElementsByTagName('html')[0].innerHTML);")
                        }
                    }
                }
                "QZ","XZF","ZNMZ","SCGCZYJS" -> {
                    webview_school.loadUrl("javascript:window.local_obj.showSource(document.getElementsByTagName('html')[0].innerHTML);")
                }
                "AHKJ" -> {
                    webview_school.loadUrl("javascript:checkLogin(\"form\")")
//                    webview_school.loadUrl("http://jwxt.ahstu.edu.cn/eams/home.action")
//                    webview_school.webViewClient = object : WebViewClient(){
//                        override fun onPageFinished(view: WebView?, url: String?) {
//                            super.onPageFinished(view, url)
//                            webview_school.loadUrl("javascript:window.local_obj.showSource(document.getElementsByTagName('html')[0].innerHTML);")
//                        }
//                    }
                }
                "NJSJJS" -> {
                    webview_school.loadUrl("http://222.193.112.78/jwc/Students/MyCourseScheduleTable.aspx")
                    webview_school.webViewClient = object : WebViewClient(){
                        override fun onPageFinished(view: WebView?, url: String?) {
                            super.onPageFinished(view, url)
                            webview_school.loadUrl("javascript:window.local_obj.showSource(document.getElementsByTagName('html')[0].innerHTML);")
                        }
                    }
                }
                "GDSYHG" -> {
                    DialogWithoutView.newInstance(
                        "请注意",
                        "广东石油化工学院解析无需手动跳转到课表界面，只需登录即可。但是需要手动输入导入的学期，输入格式：如2019学年的第二学期，输入201902，请务必输入正确！",
                        false,
                        DialogInterface.OnClickListener { _, _ ->
                            val view = LayoutInflater.from(this).inflate(R.layout.dialog_calender_time, null, false)
                            view.findViewById<TextInputLayout>(R.id.til_count_down_time).apply {
                                hint = "请输入导入学期"
                                counterMaxLength = 6
                            }
                            val dialog = DialogWithView.newInstance(
                                view,
                                "请输入导入的学期",
                                false,
                                DialogInterface.OnClickListener { _, _ ->
                                    try {
                                        val time = view.findViewById<AppCompatEditText>(R.id.edit_calender_time).text.toString().toInt()
                                        webview_school.loadUrl("http://210.38.250.43/xsgrkbcx!xsAllKbList.action?xnxqdm=$time")
                                        webview_school.webViewClient = object : WebViewClient(){
                                            override fun onPageFinished(view: WebView?, url: String?) {
                                                super.onPageFinished(view, url)
                                                webview_school.loadUrl("javascript:window.local_obj.showSource(document.getElementsByTagName('html')[0].innerHTML);")
                                            }
                                        }
                                    }catch (e: Exception){
                                        Toasty.error(this, "输入有问题呀~").show()
                                    }

                                },
                                null)
                            dialog.show(supportFragmentManager, "")
                        },
                        null
                    ).show(supportFragmentManager, "")
                }
            }
        }
    }



    inner class InJavaScriptLocalObj {
        @JavascriptInterface
        fun showSource(html: String){
            LoadLessonUtils.initSchoolLesson(TimetableRepository(this@LoadSchoolLessonWebViewActivity), html, object : LoginCallBack{
                override fun onSuccess() {
                    setResult(TagHelper.LOADSCHOOL)
                    finish()
                }

                override fun onFail(status: String) {
                    Toasty.info(this@LoadSchoolLessonWebViewActivity, status).show()
                }

            }, this@LoadSchoolLessonWebViewActivity, supportFragmentManager, intent.getBundleExtra("bundle").getString("type"))
        }
    }
}
